/*   Copyright (C) 2011 Wolfgang Hankeln, Norma J. Wendel
 *
 *   This file is part of CDinFusion.
 *
 *   CDinFusion is free software: you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public 
 *   License in version 3 (LGPL3) as published by the Free Software
 *   Foundation version 3 of the License.
 *
 *   CDinFusion is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   Lesser General Public License for more details.
 *
 *   You should have received a copy of the Lesser General Public
 *   License along with CDinFusion; see the file COPYING. If not,
 *   write to the Free Software Foundation, 59 Temple Place - Suite 330,
 *   Boston, MA 02111-1307, USA or see <http://www.gnu.org/licenses/>.
 *   
 *   If you have any questions, send an email to: megx@mpi-bremen.de.
 */
package org.cdinfusion.web.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.cdinfusion.data.CDElement;
import org.cdinfusion.filehandling.FastaAndStruturedCommentWriter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import de.mpi_bremen.mgg.FastaValidator.FastaHandlingException;
import de.mpi_bremen.mgg.FastaValidator.FastaValidator;
import de.mpi_bremen.mgg.FastaValidator.FastaValidatorException;

public class Download_Changes_Controller extends AbstractController {
	public ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		System.out.println("##### Download_Changes_Controller #####");
		Timestamp tstamp = new Timestamp(System.currentTimeMillis());
		System.out.println("download start tstamp: " + tstamp + " "
				+ tstamp.getTime());

		HttpSession session = request.getSession();
		String context_exists = "yes";
		session.setAttribute("context_exists", context_exists);
		@SuppressWarnings("unchecked")
		final List<CDElement> cdeLIST = (List<CDElement>) session
				.getAttribute("cdeLIST");
		@SuppressWarnings("unchecked")
		final List<String> allSequenceIDs = (List<String>) session
				.getAttribute("allSequenceIDs");
		int step = 0;
		if (request.getParameter("submit") == null) {
			step = Integer.parseInt(request.getParameter("step"));
		} else {
			step = 6;
		}

		String origin = (String) session.getAttribute("origin");
		String sessionID = request.getSession().getId();
		String opt_2b = (String) session.getAttribute("opt_2b");
		ModelAndView mav = null;

		session.setAttribute("origin", origin);

		if (step == 6) {// choice.contains("finish")
			mav = new ModelAndView("6_END_DOWNLOAD");
			try {

				final long start = System.currentTimeMillis();
				final String folder = System.getenv("CATALINA_HOME")
						+ "/webapps/CDinFusion/data/";
				final FastaAndStruturedCommentWriter writer = new FastaAndStruturedCommentWriter(
						folder, sessionID, cdeLIST);
				final FastaValidator fastaValidator = new FastaValidator(writer);
				fastaValidator.validate(folder + "/raw_" + sessionID + ".fasta");
				final long end = System.currentTimeMillis();
				System.out.println("Files generated in " + (end - start) + "ms");
				session.removeAttribute("cdeLIST");
				session.removeAttribute("allSequenceIDs");
			} catch (final FastaHandlingException e) {
				System.out.println("Error in Download_Changes_Controller: "
						+ e.getMessage());
				e.printStackTrace();
				
				ModelAndView maverr = new ModelAndView("ErrorPage");
				e.printStackTrace();
				maverr.addObject("errmsg", e.getMessage());
				maverr.addObject("origin", origin);
			} catch (final FastaValidatorException e) {
			    	System.out.println("Error in Download_Changes_Controller. The uploaded fasta file is invalid: "
					+ e.getMessage());
			    	e.printStackTrace();
			    
			    	ModelAndView maverr = new ModelAndView("ErrorPage");
				e.printStackTrace();
			        maverr.addObject("errmsg", "The uploaded fasta file is invalid: "+  e.getMessage());
				maverr.addObject("origin", origin);
			}

		}
		if (step == 2) {// choice.contains("change groups")
			if (allSequenceIDs.size() > 1) {
				mav = new ModelAndView("2b_GSC_SELECTED_ntom");
			} else {
				mav = new ModelAndView("2a_GSC_SELECTED_1to1");
			}
		}
		if (step == 3) {// input form choice.contains("change c.d. entries")
			if (allSequenceIDs.size() > 1) {
				if (opt_2b.equals("one")) {
					mav = new ModelAndView("3b_CD_INPUT_1tom");
				} else {// if(opt_2b.equals("many"))
					mav = new ModelAndView("cd_changes_in_x");
				}
			} else {
				mav = new ModelAndView("3a_CD_INPUT_1to1");
			}
		}
		if (step == 4) {
			mav = new ModelAndView("4_MAPPING");
		}

		if (step == 1) {// choice.contains("upload FASTA file")
			mav = new ModelAndView("1_START_FASTA");
		}

		mav.addObject("origin", origin);
		return mav;
	}
}
